const { getUserInfo } = require('../service/user.service');
const {
    userFormatError,
    userRegisterError,
    userAlreadyExisted,
} = require('../constant/error.type');

const userValidator = async (ctx, next) => {
    const { user_name, pass_word } = ctx.request.body;
    // 1.叛断用户名和密码是否为空
    if (!user_name || !pass_word) {
        // ctx.body = {
        //     code: '10001',
        //     result: null,
        //     message: '用户名或密码不能为空'
        // }
        ctx.app.emit('error', userFormatError, ctx);
        return;
    }
    await next();
}

// 2.判断用户名是否合法
const veryfyUserName = async (ctx, next) => {
    const { user_name } = ctx.request.body;
    try {
        const result = await getUserInfo({ user_name })
        if (!result) {
            // ctx.body = {
            //     code: '10002',
            //     result: null,
            //     message: '用户名已存在'
            // }
            ctx.app.emit('error', userAlreadyExisted, ctx);
            return;
        }
    } catch (error) {
        console.log(error, 'error')
        ctx.app.emit('error', userRegisterError, ctx);
        return;
    }
    await next();
}

module.exports = {
    userValidator,
    veryfyUserName
}